package tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Entity;
import android.os.Environment;

public class HttpUtils {

	/**
	 * 下载apk
	 * 
	 * @param path
	 * @return
	 */
	public static String downloadAPK(String path) {
		String apkPathString = "";
		byte[] data = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(path);
		// 得到sdcard 根路径
		File file = Environment.getExternalStorageDirectory();
		FileOutputStream fileOutputStream = null;
		try {
			HttpResponse httpResponse = httpClient.execute(httpGet);
			// 页面请求的状态值，分别有：200请求成功、303重定向、400请求错误、401未授权、403禁止访问、404文件未找到、500服务器错误
			// 20141113 解决报404 问题，网址：http://www.jb51.net/article/30140.htm
			// IIS 默认不支持.apk 后缀的下载，需要设置 右键“属性-http头-mime类型-添加-扩展名:.apk 类型:application/vnd.android.package-archive“
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 得到数据
				data = EntityUtils.toByteArray(httpResponse.getEntity());
				// 判读sd card 是否被挂载
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					// 写入文件到根目录下
					fileOutputStream = new FileOutputStream(new File(file,
							"LoginDesign.apk"));
					fileOutputStream.write(data, 0, data.length);
				}
				apkPathString = file.getAbsolutePath() + "/"
						+ "LoginDesign.apk";
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return apkPathString;
	}
}
